package com.whsxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.whsxt.dao.ProdEsDao;
import com.whsxt.domain.Prod;
import com.whsxt.domain.ProdComm;
import com.whsxt.domain.User;
import com.whsxt.es.ProdEs;
import com.whsxt.feign.ProdCommMemberFeign;
import com.whsxt.mapper.ProdCommMapper;
import com.whsxt.mapper.ProdMapper;
import com.whsxt.service.ProdCommService;
import com.whsxt.vo.ProdCommResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author: caoqingwen
 * @CreateTime: 2021-03-15 14:19
 * @Description: ${Description}
 */
@Service
@Slf4j
public class ProdCommServiceImpl extends ServiceImpl<ProdCommMapper, ProdComm> implements ProdCommService {


    @Autowired
    private ProdCommMapper prodCommMapper;

    @Autowired
    private ProdMapper prodMapper;

    @Autowired
    private ProdEsDao prodEsDao;

    @Autowired
    private ProdCommMemberFeign prodCommMemberFeign;


    /**
     * 分页查询商品评论
     *
     * @param page
     * @param prodComm
     * @return
     */
    @Override
    public IPage<ProdComm> findProdCommPage(Page<ProdComm> page, ProdComm prodComm) {
        //排序
        page.addOrder(OrderItem.desc("rec_time"));
        //分页查询
        String prodName = prodComm.getProdName();
        List<Long> ids = null;
        if (StringUtils.isNotBlank(prodName)) {
            //商品名称不为空，就先根据商品名称查询商品表得到商品id
            List<Prod> prods = prodMapper.selectList(new LambdaQueryWrapper<Prod>()
                    .like(StringUtils.isNotBlank(prodName), Prod::getProdName, prodName)
            );
            if (!CollectionUtils.isEmpty(prods)) {
                ids = prods.stream().map(Prod::getProdId).collect(Collectors.toList());
            }
        }

        //分页查评论
        Page<ProdComm> prodCommPage = prodCommMapper.selectPage(page, new LambdaQueryWrapper<ProdComm>()
                .eq(prodComm.getStatus() != null, ProdComm::getStatus, prodComm.getStatus())
                .in(!CollectionUtils.isEmpty(ids), ProdComm::getProdId, ids)
        );

        List<ProdComm> prodCommList = prodCommPage.getRecords();
        if (!CollectionUtils.isEmpty(prodCommList)) {
            //组装商品的名称
            List<Long> newProdIds = prodCommList.stream().map(ProdComm::getProdId).collect(Collectors.toList());
            List<Prod> prods = prodMapper.selectBatchIds(newProdIds);
            prodCommList.forEach(ps -> {
                Prod prod = prods.stream().filter(pds -> pds.getProdId().equals(ps.getProdId())).collect(Collectors.toList()).get(0);
                ps.setProdName(prod.getProdName());
            });
        }
        return prodCommPage;
    }


    /**
     * 前台查询商品的评论总览
     *
     * @param prodId
     * @return
     */
    @Override
    public ProdCommResult getFrontProdComm(Long prodId) {
        ProdCommResult prodCommResult = new ProdCommResult();
        //从es中拿好评率
        Optional<ProdEs> optional = prodEsDao.findById(prodId);
        ProdEs prodEs = optional.get();
        //好评率
        BigDecimal positiveRating = prodEs.getPositiveRating();
        //好评数
        Long praiseNumber = prodEs.getPraiseNumber();
        //总评数
        Integer totalCount = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
        );

        Integer secondCount = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(ProdComm::getEvaluate, 1)
        );

        Integer badCount = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(ProdComm::getEvaluate, 2)
        );

        Integer picCount = prodCommMapper.selectCount(new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .isNotNull(ProdComm::getPics)
        );

        prodCommResult.setNumber(totalCount);
        prodCommResult.setPicNumber(picCount);
        prodCommResult.setSecondaryNumber(secondCount);
        prodCommResult.setNegativeNumber(badCount);
        prodCommResult.setPositiveRating(positiveRating);
        prodCommResult.setPraiseNumber(praiseNumber);

        return prodCommResult;
    }


    /**
     * 前台查询商品的评论
     *
     * @param page
     * @param prodId
     * @param evaluate
     * @return
     */
    @Override
    public Page<ProdComm> getFrontProdCommPage(Page<ProdComm> page, Long prodId, Integer evaluate) {
        //查询
        Page<ProdComm> prodCommPage = prodCommMapper.selectPage(page, new LambdaQueryWrapper<ProdComm>()
                .eq(ProdComm::getProdId, prodId)
                .eq(evaluate != -1, ProdComm::getEvaluate, evaluate)
                .orderByDesc(ProdComm::getRecTime)
        );
        List<ProdComm> prodCommList = prodCommPage.getRecords();
        if (!CollectionUtils.isEmpty(prodCommList)) {
            //查询用户信息，远程调用获取用户信息
            List<String> userIds = prodCommList.stream().map(ProdComm::getUserId).collect(Collectors.toList());
            List<User> userList = prodCommMemberFeign.findUserInfoByUserIds(userIds);
            if (!CollectionUtils.isEmpty(userList)) {
                //如果远程调用失败，没有用户信息，也要正常返回，前台给用户一个默认值
                prodCommList.forEach(prodComm -> {
                    User user1 = userList.stream()
                            .filter(user -> user.getUserId().equals(prodComm.getUserId()))
                            .collect(Collectors.toList())
                            .get(0);
                    prodComm.setNickName(user1.getNickName());
                    prodComm.setPic(user1.getPic());
                });
            }
        }
        return prodCommPage;
    }
}
